package cz.kfad.ofrss.common;

import android.app.Activity;
import android.os.AsyncTask;
import android.widget.Toast;
import cz.kfad.ofrss.R;
import cz.kfad.ofrss.activity.CategoriesActivity;
import cz.kfad.ofrss.activity.CategoryActivity;
import cz.kfad.ofrss.backend.BackendService;
import cz.kfad.ofrss.backend.IBackend;
import cz.kfad.ofrss.model.Category;

public class AsynCategory extends AsyncTask<Category, Void, Void> {

    private Activity context;

    @Override
    protected void onPreExecute() {
        Toast.makeText(context, context.getString(R.string.categoryWillBeProcessed), Toast.LENGTH_SHORT).show();
    }

    @Override
    protected Void doInBackground(Category... params) {
        Category category = params[0];
        IBackend backend = BackendService.createBackend(context);
        if (category.getId() > 0) {
            backend.editCategory(category);
        } else {
            backend.saveCategory(category);
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        if (context instanceof CategoriesActivity) {
            ((CategoriesActivity) context).reload();
        } else if (context instanceof CategoryActivity) {
            ((CategoryActivity) context).reload();
        }
    }

    public void setContext(Activity context) {
        this.context = context;
    }

}
